package com.marketingcenter.service.impl;

import com.marketingcenter.entity.Promotion;
import org.springframework.data.jpa.repository.JpaRepository;
import com.marketingcenter.repository.*;
import com.marketingcenter.service.PromotionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 营销活动通用服务实现类
 */
@Service
public abstract class PromotionServiceImpl<T extends Promotion> implements PromotionService<T> {

    protected abstract JpaRepository<T, Long> getRepository();

    @Override
    public T create(T promotion) {
        promotion.setCreateTime(LocalDateTime.now());
        promotion.setUpdateTime(LocalDateTime.now());
        return getRepository().save(promotion);
    }

    @Override
    public T update(T promotion) {
        promotion.setUpdateTime(LocalDateTime.now());
        return getRepository().save(promotion);
    }

    @Override
    public void delete(Long id) {
        getRepository().deleteById(id);
    }

    @Override
    public T findById(Long id) {
        return getRepository().findById(id).orElse(null);
    }

    @Override
    public List<T> findAll() {
        return getRepository().findAll();
    }

    @Override
    public List<T> findByStatus(Integer status) {
        // 这个方法需要在具体的实现类中重写，因为每个实体类的Repository接口中的方法名可能不同
        throw new UnsupportedOperationException("Method not implemented");
    }

    @Override
    public List<T> findActivePromotions() {
        LocalDateTime now = LocalDateTime.now();
        // 这个方法需要在具体的实现类中重写，因为每个实体类的Repository接口中的方法名可能不同
        throw new UnsupportedOperationException("Method not implemented");
    }

    @Override
    public void enable(Long id) {
        T promotion = findById(id);
        if (promotion != null) {
            promotion.setStatus(1); // 1表示进行中
            update(promotion);
        }
    }

    @Override
    public void disable(Long id) {
        T promotion = findById(id);
        if (promotion != null) {
            promotion.setStatus(3); // 3表示已停用
            update(promotion);
        }
    }

}